package com.hserver.test;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.github.dockerjava.jaxrs.JerseyDockerHttpClient;
import com.github.dockerjava.netty.NettyDockerCmdExecFactory;
import com.hserver.docker.config.ConstConfig;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

//https://github.com/docker-java/docker-java/issues/481
public class StreamDockerExec {

    public static void main(String[] args) throws InterruptedException, UnsupportedEncodingException {


        DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost("tcp://xx.xx.218.193:9393")
                .build();

        NettyDockerCmdExecFactory factory = new NettyDockerCmdExecFactory();

        DockerClient dockerClient = DockerClientBuilder.getInstance(config)
                .withDockerCmdExecFactory(factory)
                .build();

        InputStream stdin = new ByteArrayInputStream("ls\n".getBytes());

        ByteArrayOutputStream stdout = new ByteArrayOutputStream();

        ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd("6eb53758438863ec6aff640379c72494eeb9f78685d33767dc9393576c838e4a")
                .withAttachStdout(true)
                .withAttachStdin(true)
                .withTty(false)
                .withCmd("/bin/sh").exec();

        dockerClient.execStartCmd(execCreateCmdResponse.getId())
                .withDetach(false)
                .withStdIn(stdin)
                .exec(new ExecStartResultCallback(stdout, System.err))
                .awaitCompletion();
        System.out.println(new String(stdout.toByteArray(), "utf-8"));
    }


}
